package com.yuri.news.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.yuri.news.entity.News;
import com.yuri.news.jpa.NewsRepository;
import com.yuri.news.service.NewsService;
@Service
public class NewsServiceImpl implements NewsService {
	@Autowired
	NewsRepository newsRepository;
	@Override
	public News saveNews(News news) {
		//设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		news.setDate(df.format(new Date()));
		news.setCount(0);
		
		if(null == news.getUrl()) {
			
		}
		if(news.getUrl() != null && "".equals(news.getUrl())) {
			news.setUrl("../static/img/1.jpg");
		}
		return newsRepository.save(news);
	}

	@Override
	public Boolean updapeNews(News news) {
		Boolean flag = false;
		Optional<News> optional = newsRepository.findById(news.getId());
		if(optional.isPresent()) {
			newsRepository.save(news);
			flag = true;
		}
		return flag;
	}

	@Override
	public void deleteNews(News news) {
		newsRepository.delete(news);
	}

	@Override
	public Page<News> listNews(Pageable page) {
		return newsRepository.findAll(page);
	}

	@Override
	public News getNewsById(Long id) {
		Optional<News> optional = newsRepository.findById(id);
		if(optional.isPresent()) {
			// 将新闻的访问次数+1
			News news = optional.get();
			news.setCount(news.getCount()+1);
			newsRepository.save(news);
			
			return news;
		}else {
			return null;
		}
	}

	@Override
	public Page<News> listNewsByKey(String key, Pageable page) {
		Page<News> newss = null;
		if("".equals(key)) {
			newss = newsRepository.findAll(page);
		} else if(newsRepository.findNewsByClassName(key).size() > 0) {
			newss = newsRepository.findNewsByClassName(key,page);
		}else {
			newss = newsRepository.findByTitleLike("%"+key+"%", page);
		}
		return newss;
	}

	@Override
	public Page<News> listNewsByClassName(String className, Pageable page) {
		// TODO Auto-generated method stub
		return null;
	} 

	@Override
	public Page<News> listNewsByClassId(Long classId, Pageable page) {
		Page<News> pageNews = null;
		pageNews = newsRepository.findNewsByClassId(classId, page);
		
		return pageNews;
	}

	@Override
	public Page<News> listHotNews(Pageable page) {
		// TODO Auto-generated method stub
		
		return null;
	}
}
